package com.carhailing.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.carhailing.common.result.Result;
import com.carhailing.system.domain.User;
import com.carhailing.system.mapper.UserEnrollInviteMapper;
import com.carhailing.system.service.UserEnrollInviteService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @Author: Gd
 * @package: com.carhailing.system.service.impl
 * @Project: carhailing
 * @Name: UserEnrollInviteServiceImpl
 * @Date: 2024-7-19 20:41
 */
@Service
@Log4j2
public class UserEnrollInviteServiceImpl implements UserEnrollInviteService {

    @Autowired
    private UserEnrollInviteMapper userEnrollInviteMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HttpServletRequest request;

    private static final String originalurl = "http://localhost:9002/userEnroll?userPhone=";

    private static final String ALGORITHM = "AES";

    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    @Override
    public Result userEnroll(String userPhone, String encryptedPageNum) {

        String s = redisTemplate.opsForValue().get(encryptedPageNum);
        User user = JSONObject.parseObject(s, User.class);
        if(user.getInviterCode() == null ){
            return Result.error("该用户邀请码不匹配");
        }
        // 判断新用户手机号是否被注册过
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_phone",userPhone);
        List<User> users = userEnrollInviteMapper.selectByMap(map);
        // 日志记录是否有该用户
        log.info(users.isEmpty()?"无记录":users.get(0).getUserPhone());
        // 根据手机号查询用户信息
        //判断用户信息是否存在
        if (!users.isEmpty()){
            //插入用户
            User user1 = new User();
            user1.setUserPhone(userPhone);
            LocalDateTime now = LocalDateTime.now();
            Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
            user1.setRegistertime(date);
            userEnrollInviteMapper.insert(user1);
            // 给新用户添加优惠券
            userEnrollInviteMapper.insertCouponsToNewUser(user1);
        }
        // 解密电话号码
        try {
            SecretKey secretKey = generateKey(128);
            String decryptedPhoneSecret = decrypt(encryptedPageNum, secretKey);
            System.out.println("【解密后的电话号码】：" + decryptedPhoneSecret);
            // 手机号匹配  给用户发优惠券
            if(decryptedPhoneSecret.equals(user.getUserPhone())){
//                userEnrollInviteMapper.insertCouponsToOlderUser(1,2);
                userEnrollInviteMapper.insertCouponsToOlderUser(user);
            }
//            System.out.println("【解密后的邀请码】：" + (originalurl + decryptedPhoneSecret));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    @Override
    public Result getInviteUrl() {

        // 缓存取出用户信息
//        String token = request.getHeader(TokenConstants.TOKEN);
//        String userKey = JwtUtils.getUserKey(token);
//        String user = redisTemplate.opsForValue().get(JwtConstants.USER_KEY + userKey);
//        User users = JSON.parseObject(user, User.class);
        // 生成邀请好友链接
        // 生成AES密钥
        String encryptedUrl = null ;
        try {
            SecretKey secretKey = generateKey(128);
            // 加密 userPhone
            String userPhoneSecret = "17739555294";// 获取到 userPhone
//            String userPhoneSecret = users.getUserPhone();// 获取到 userPhone
            String encryptedPageNum = encrypt(userPhoneSecret, secretKey);
            // 密文手机号存入缓存  key：encryptedPageNum   value: user
//            redisTemplate.opsForValue().set(encryptedPageNum, JSON.toJSONString(users));
            // 构建加密后的URL
            encryptedUrl  = originalurl.replace("userPhone=", "userPhone=" + encryptedPageNum);
            System.out.println("【邀请码】：" + encryptedUrl);
            // 更新用户邀请码
//            userEnrollInviteMapper.updateInviterCode(encryptedUrl, users.getUserPhone());
            userEnrollInviteMapper.updateInviterCode(encryptedUrl, "17739555294");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success(encryptedUrl);
    }




    //生成密钥
    public static SecretKey generateKey(int keySize) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(keySize);
        return keyGenerator.generateKey();
    }

    // AES加密
    public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密方法
    public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
        Key key = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

        return new String(original);
    }
}
